package com.css.fxfzfxqh.modules.util.hypergraph.controller;

import com.css.fxfzfxqh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzfxqh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.common.utils.ZipDownloadUtil;
import com.css.fxfzfxqh.modules.util.hypergraph.entity.NetworkanalystVersion;
import com.css.fxfzfxqh.modules.util.hypergraph.service.HypergraphService;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.PlatformPageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: fxfzfxqh
 * @Author: lhl
 * @CreateDate: 2023/6/5 14:26
 * 超图
 */
@RestController
@RequestMapping("/hypergraph")
public class HypergraphController {

    @Resource
    HypergraphService hypergraphService;
    @Autowired
    private AttachmentInfoService attachmentInfoService;

    /**
     * 获取超图server口令
     * @return
     */
    @PostMapping("/getServerToken")
    public RestResponse getServerToken(@RequestBody Map<String, Object> map){
        RestResponse restResponse=null;
        try {
            restResponse=hypergraphService.getServerToken(map);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    // /**
    //  * tif发布超图服务工具--创建任务
    //  * @return
    //  */
    // @PostMapping("/tifMapLayerToolJobPost")
    // public RestResponse tifMapLayerToolJobPost(@RequestBody Map<String,String> map){
    //     RestResponse restResponse=null;
    //     try {
    //         restResponse=hypergraphService.tifMapLayerToolJobPost(map.get("layerName"),map.get("serverToken"));
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         restResponse=RestResponse.fail("获取失败！");
    //     }
    //     return restResponse;
    // }
    //
    // /**
    //  * tif发布超图服务工具--根据ID查询任务信息
    //  * @return
    //  */
    // @PostMapping("/tifMapLayerToolJobGet")
    // public RestResponse tifMapLayerToolJobGet(@RequestBody Map<String,String> map){
    //     RestResponse restResponse=null;
    //     try {
    //         restResponse=hypergraphService.tifMapLayerToolJobGet(map.get("jobID"),map.get("serverToken"));
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         restResponse=RestResponse.fail("获取失败！");
    //     }
    //     return restResponse;
    // }

    //SQL查询超图图层数据
    @PostMapping("/mapSqlQueryResultsPost")
    public RestResponse mapSqlQueryResultsPost(@RequestBody Map<String, Object> map){
        RestResponse restResponse=null;
        try {
            String layerUrl = (String) map.get("layerUrl");
            String datasource = (String) map.get("datasource");
            String dataset = (String) map.get("dataset");
            String networkType = (String) map.get("networkType");
            String sqlFilter = (String) map.get("sqlFilter");
            restResponse=hypergraphService.mapSqlQueryResultsPost(layerUrl,datasource, dataset, networkType, sqlFilter);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    //下游追踪
    @GetMapping("/networkTracedown")
    public RestResponse networkTracedown(String layerUrl,String nodeID, String edgeID, boolean isUncertainDirectionValid, boolean returnFeatures){
        RestResponse restResponse=null;
        try {
            restResponse=hypergraphService.networkTracedown(layerUrl, nodeID, edgeID, isUncertainDirectionValid, returnFeatures);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    //上游追踪
    @GetMapping("/networkTraceup")
    public RestResponse networkTraceup(String layerUrl,String nodeID, String edgeID, boolean isUncertainDirectionValid, boolean returnFeatures){
        RestResponse restResponse=null;
        try {
            restResponse=hypergraphService.networkTraceup(layerUrl, nodeID, edgeID, isUncertainDirectionValid, returnFeatures);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    //爆管分析
    @GetMapping("/networkBurstanalyse")
    public RestResponse networkBurstanalyse(String layerUrl, String sourceNodeIDs, String nodeID, String edgeID, boolean isUncertainDirectionValid, boolean returnFeatures){
        RestResponse restResponse=null;
        try {
            restResponse=hypergraphService.networkBurstanalyse(layerUrl, sourceNodeIDs, nodeID, edgeID, isUncertainDirectionValid, returnFeatures);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    //连通性分析
    @GetMapping("/networkConnectededges")
    public RestResponse networkConnectededges(String layerUrl, String nodeIDs, String edgeIDs, boolean connected, boolean returnFeatures){
        RestResponse restResponse=null;
        try {
            restResponse=hypergraphService.networkConnectededges(layerUrl, nodeIDs, edgeIDs, connected,returnFeatures);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /**
     * 工作空间发布设施网络分析服务
     * @return
     */
    @PostMapping("/newWorkspaceNetworkVersion")
    public RestResponse newWorkspaceNetworkVersion(@RequestBody NetworkanalystVersion networkanalystVersion){
        RestResponse restResponse=null;
        try {
            //根据任务ID逻辑删除交通网络分析服务版本信息
            hypergraphService.deleteNetworkanalystVersionByTaskId(networkanalystVersion.getTaskId());
            String attachIds = networkanalystVersion.getAttachIds();
            String[] ids = attachIds.split(",");
            for(int i=0;i<ids.length;i++){
                //根据id和文件名获取真实的放在磁盘上的文件
                AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(ids[i]);
                String attachName = attachmentInfoEntity.getAttachName();
                String attachPath = attachmentInfoEntity.getAttachPath();
                String fileDirId = attachmentInfoEntity.getFileDirId();
                fileDirId = fileDirId.replace('\\','/');
                String url = fileDirId + attachPath;
                if(attachName.endsWith(".smwu")){
                    networkanalystVersion.setSmwuUrl(url);
                }else if(attachName.endsWith(".udbx")){
                    networkanalystVersion.setUdbxUrl(url);
                }
            }
            restResponse=hypergraphService.newWorkspaceNetworkVersion(networkanalystVersion);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("发布失败！");
        }
        return restResponse;
    }

    /**
     * 批量逻辑删除交通网络分析服务版本列表
     * @return
     */
    @PostMapping("/deleteNetworkanalystVersion")
    public RestResponse deleteNetworkanalystVersion(@RequestBody Map<String, Object> map){
        RestResponse restResponse=null;
        try {
            String idsStr = (String) map.get("idsStr");
            restResponse=hypergraphService.deleteNetworkanalystVersion(idsStr);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    /**
     * 查询交通网络分析服务版本列表
     * @return
     */
    @GetMapping("/getNetworkVersionList")
    public RestResponse getNetworkVersionList(HttpServletRequest request, NetworkanalystVersion networkanalystVersion){
        RestResponse restResponse=null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            networkanalystVersion.setCurPage(1);
            networkanalystVersion.setPageSize(1);
            restResponse=hypergraphService.getNetworkVersionList(networkanalystVersion);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    //网络拓扑计算功能失效等级
    @PostMapping("/countNetworkanalyst")
    public RestResponse countNetworkanalyst(@RequestBody NetworkanalystVersion networkanalystVersion){
        RestResponse restResponse=null;
        try {
            restResponse=hypergraphService.countNetworkanalyst(networkanalystVersion);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }

    /**
     * 批量下载超图路网工作空间文件
     * @return
     */
    @PostMapping("/downloadNetworkFileZip")
    public RestResponse downloadNetworkFileZip(HttpServletResponse response, String id) {
        RestResponse restResponse=null;
        try{
            NetworkanalystVersion networkanalystVersion = hypergraphService.getNetworkVersionById(id);
            String smwuUrl = networkanalystVersion.getSmwuUrl();
            String udbxUrl = networkanalystVersion.getUdbxUrl();
            String tempFileName = "超图工作空间数据编号" + networkanalystVersion.getVersion();
            int lastIndex = smwuUrl.lastIndexOf("/");
            String newUploadPath = smwuUrl.substring(0, lastIndex+1);
            //获取指定路径下的文件
            File file = new File(smwuUrl);
            File file1 = new File(udbxUrl);
            List<File> _files = new ArrayList<>();
            _files.add(file);
            _files.add(file1);
            List<File> zipFiles = _files;
            StringBuffer sb = new StringBuffer();
            if (!CollectionUtils.isEmpty(zipFiles)) {
                String zipName = tempFileName + ".zip";
                String msg = ZipDownloadUtil.zipDownload(response, newUploadPath, zipName, zipFiles);
                sb.append(msg);
            } else {
                String zipName = tempFileName + ".zip";
                String msg = ZipDownloadUtil.zipDownload(response, newUploadPath, zipName, new ArrayList<File>());
                sb.append(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("查询失败！");
        }
        return restResponse;
    }

    //根据sql导出shp文件并下载zip
    @PostMapping("/downloadShpFileBySql")
    public RestResponse downloadShpFileBySql(HttpServletResponse response, String dataset, String sqlFilter) {
        try {
            String timeStamp = System.currentTimeMillis() + "";//时间戳，用于数据集名称后缀，防止重名
            String datasource = "fxfzfxqh";
            //导出shp文件
            String resultFilePath = hypergraphService.exportShpFile(datasource,dataset,sqlFilter,timeStamp);
            if (PlatformObjectUtils.isEmpty(resultFilePath)) {
                return RestResponse.fail("导出失败!");
            }else{
                String affiliatedFileName = dataset;
                //获取指定路径下的所有文件名
                File file = new File(resultFilePath);
                File[] files = file.listFiles();
                if (files == null) {
                    return RestResponse.fail("下载失败，该目录下不存在文件");
                }
                String tempFileName = affiliatedFileName;
                String _temp = "";
                List<File> _files = new ArrayList<>();
                for (int i = 0; i < files.length; i++) {
                    _temp = files[i].getName();
                    if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
                }
                List<File> zipFiles = _files;
                //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
                StringBuffer sb = new StringBuffer();
                if (!CollectionUtils.isEmpty(zipFiles)) {
                    String zipName = tempFileName + ".zip";
                    String msg = ZipDownloadUtil.zipDownload(response, resultFilePath, zipName, zipFiles);
                    sb.append(msg);
                } else {
                    String zipName = tempFileName + ".zip";
                    String msg = ZipDownloadUtil.zipDownload(response, resultFilePath, zipName, new ArrayList<File>());
                    sb.append(msg);
                }
            }

            return RestResponse.succeed("导出成功");
        } catch (Exception e) {
            return RestResponse.fail("导出失败!");
        }
    }

    //查询生命线分析点、线数据的范围经纬度列表
    @GetMapping("/getSmxEvaluationResultExtentLonLatList")
    public RestResponse getSmxEvaluationResultExtentLonLatList(String taskId,String qcType){
        RestResponse restResponse=null;
        try {
            restResponse=RestResponse.succeed(hypergraphService.getSmxEvaluationResultExtentLonLatList(taskId,qcType));
        } catch (Exception e) {
            e.printStackTrace();
            restResponse=RestResponse.fail("获取失败！");
        }
        return restResponse;
    }
}
